# app.py
from flask import Flask, request, jsonify
from flask_cors import CORS
from models import Student, init_db

app = Flask(__name__)
CORS(app)

# 初始化数据库（连接、建表、预置数据）
init_db()

@app.route('/students', methods=['GET'])
def get_students():
    students = Student.select()
    return jsonify([s.to_dict() for s in students])

@app.route('/students', methods=['POST'])
def add_student():
    data = request.json
    student = Student.create(**data)
    return jsonify({'message': '添加成功', 'id': student.id})

@app.route('/students/<int:student_id>', methods=['PUT'])
def update_student(student_id):
    data = request.json
    student = Student.get_by_id(student_id)
    for key, value in data.items():
        setattr(student, key, value)
    student.save()
    return jsonify({'message': '更新成功'})

@app.route('/students/<int:student_id>', methods=['DELETE'])
def delete_student(student_id):
    student = Student.get_by_id(student_id)
    student.delete_instance()
    return jsonify({'message': '删除成功'})

@app.route('/students/export', methods=['GET'])
def export_students():
    students = Student.select()
    data = [s.to_dict() for s in students]
    return jsonify(data)


if __name__ == '__main__':
    app.run(debug=True)


